package lt.marsrutai.mobile.android.task;

import java.util.List;

import lt.marsrutai.mobile.android.AppContext;
import lt.marsrutai.mobile.android.R;
import lt.marsrutai.mobile.android.exception.DataAccessException;
import lt.marsrutai.mobile.android.model.MobileScope;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;

/**
 *
 * @author Martynas
 *
 */
public class GetAvailableScopesTask extends AsyncTask<Void, Void, List<MobileScope>>{

    private static final Logger logger = LoggerFactory.getLogger("GetAvailableScopesTask");

    private ProgressDialog progressDialog;

    private Activity activity;

    public GetAvailableScopesTask(Activity activity) {
        this.activity = activity;
    }

    @Override
    protected void onPreExecute() {
        // Show a loading dialog, which can be cancelled
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progressDialog = new ProgressDialog(activity);
                progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                progressDialog.setTitle(activity.getString(R.string.available_scopes_loading_title));
                progressDialog.setMessage(activity.getString(R.string.available_scopes_loading_message));
                progressDialog.setCancelable(true);
                progressDialog.setIndeterminate(true);
                progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

                    @Override
                    public void onCancel(DialogInterface dialog) {
                        GetAvailableScopesTask.this.cancel(true);
                    }
                });

                progressDialog.show();
            }
        });
    }

    @Override
    protected List<MobileScope> doInBackground(Void... params) {

        try {
            return AppContext.getDataService().getMobileScopes();
        }
        catch (DataAccessException e) {
            logger.warn("Unamble to download available scope list.", e);
        }

        return null;
    }

    @Override
    protected void onPostExecute(List<MobileScope> result) {

        // close the progress dialog
        progressDialog.dismiss();
    }

}
